const Base = require('./base.js');
var request = require('request');
var path = require('path')
var fs = require('fs')

async function downloadUrl (uri, filename){
  return await new Promise((resolve) => {
    var stream = fs.createWriteStream(filename);
    request(uri).pipe(stream).on('close', resolve)
  })
}

function getFilePath () {
  let timestamp = Date.now()
  var fileDir = path.join(
    think.ROOT_PATH, 'www', 'uploads', think.datetime(timestamp, 'YYYY'), think.datetime(timestamp, 'MMDD')
  )
  think.mkdir(fileDir)
  return {
    path: fileDir,
    url: 'uploads/' + think.datetime(timestamp, 'YYYY') + '/' + think.datetime(timestamp, 'MMDD') + '/'
  }
}

module.exports = class extends Base {
  indexAction() {
    var file = this.file('file')
    if (!file) return this.json({
      status: -1, message: '没有上传文件'
    })
    if (!Array.isArray(file)) file = [file]
    var result = []
    file.forEach((item) => {
      var pathobj = getFilePath()
      let filename = think.uuid('v1') + path.extname(item.path)
      let filepath = path.join(
        pathobj.path, filename
      )
      fs.renameSync(item.path, filepath)
      result.push(
        pathobj.url + filename
      )
    })
    if (result.length === 1) {
      this.json({
        status: 200,
        message: '上传成功',
        result: result[0]
      })
    } else {
      this.json({
        status: 200,
        message: '上传成功',
        result: result
      })
    }
    // fs.renameSync()
  }
  async urlAction () {
    var url = this.post('url')
    var ext = this.post('ext') || (path.extname(url) || '.jpg')
    var pathobj = getFilePath()
    let filename = think.uuid('v1') + ext
    let filepath = path.join(
      pathobj.path, filename
    )
    await downloadUrl(url, filepath)
    this.json({
      status: 200,
      message: '保存成功',
      result: pathobj.url + filename
    })
  }
};
